<?php
include __DIR__ . "/config/cors.php";
include __DIR__ . "/database.php";

$cookie = @$_COOKIE['role'];
$username = $_POST['username'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
$mail = $_POST['mail'];
$role = $_POST['role'];

if (!isset($cookie) or $cookie != "admin") {
    echo json_encode([
        "code" => 401,
        "message" => "无权访问！"
    ]);
    exit;
} else if ($username == "" or $password == "") {
    echo json_encode([
        "code" => 201,
        "message" => "用户名和密码不能为空"
    ]);
    exit;
} else if ($password != $password2) {
    echo json_encode([
        "code" => 201,
        "message" => "两次密码不一致"
    ]);
    exit;
}

$db = new DB();
// 判断用户是否已存在
$sql = "select * from user where username = '$username'";
$data = $db->selectOne($sql);
if (is_array($data) and count($data) > 0) {
    echo json_encode([
        "code" => 206,
        "message" => "$username 已存在"
    ]);
} else if (is_array($data) and count($data) == 0) {
    $sql = "insert into user (username, password, mail, register, role)
            values ('$username', '$password', '$mail', NOW(), '$role')";
    if ($db->execute($sql)) {
        echo json_encode([
            "code" => 200,
            "message" => "添加用户 $username 成功"
        ]);
    } else {
        echo json_encode([
            "code" => 205,
            "message" => "添加用户 $username 失败"
        ]);
    }
} else {
    echo json_encode([
        "code" => 205,
        "message" => "添加用户 $username 失败"
    ]);
}
